/*
 * @Author: liu wang wang
 * @Date: 2020-07-07 19:36:29
 * @LastEditTime: 2020-07-21 14:43:35
 * @LastEditors: liu wang wang
 * @Description: 独立的公用函数库
 * @FilePath: \st-sdk-js\src\tools\index.ts
 */
const string = Object.prototype.toString;

export function isDate(val: any): val is Date {
    return string.call(val) === '[object Date]'
}

export function isObject(val: any): val is Object {
    return val !== null && typeof val === 'object'
}

export function isPlainObject(val: any): val is Object {
    return string.call(val) === '[object Object]'
}
export function isArray<T>(val:any): val is Array<T>{
    return string.call(val) === '[object Array]'
}
// 序列化表单数据
export function serialization(val: HTMLCollection[]): any {
    if (val.length <= 0) { return }
    const data: any= {};
    for (let index = 0; index < val.length; index++) {
        const element: any = val[index];
        switch(element.type){
            case 'text':
                data[element.name] = element.value;
                break;
            case 'checkbox':
                if(!data[element.name]){
                    data[element.name] = [];
                }
                if(element.checked){
                    data[element.name].push(element.value);
                }
                break;
            case 'select-one':
                data[element.name] = element.value;
                break;
            case 'radio':
                if(element.checked){
                    data[element.name] = element.value;
                }
                break;
            default:
                break;
        }
    }
    return data;
}
// 淡出
export function fadeout(ele: HTMLElement):void{
    let opacity = 1;
    function ani(){
        window.requestAnimationFrame(function(){
            ele.style.opacity = opacity+'';
            if(opacity > 0){
                opacity-=0.1;
                ani();
            }else{
               ele.parentNode && (ele.parentNode as HTMLElement).removeChild(ele);
            }
        });
    }
    ani();
}
// 节流
export function throttle(func:Function, limit: number) {
    let inThrottle:Boolean
    return function() {
      const args = arguments
      if (!inThrottle) {
        func.apply(undefined, args)
        inThrottle = true
        setTimeout(() => {
          inThrottle = false
        }, limit)
      }
    }
}

export function debounce(func:Function, delay: number):Function {
    let inDebounce:number
    return function() {
      const args = arguments
      clearTimeout(inDebounce)
      inDebounce = window.setTimeout(() => func.apply(undefined, args), delay)
    }
  }